package com.js.common.utils;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
import lombok.extern.slf4j.Slf4j;

import java.io.StringWriter;
import java.util.Map;

@Slf4j
public class FreemarkerUtils {
    public static String getTemplate(String templatePath, Map<String,Object> map) {
        try {
            Configuration cfg = new Configuration(Configuration.VERSION_2_3_30);

            cfg.setClassForTemplateLoading(FreemarkerUtils.class, "/templates");

            cfg.setDefaultEncoding("UTF-8");
            cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
            cfg.setLogTemplateExceptions(true);
            Template temp = cfg.getTemplate(templatePath);
            StringWriter stringWriter = new StringWriter();
            temp.process(map, stringWriter);
            return stringWriter.toString();
        }catch (Exception e) {
            log.error("getTemplateFail", e);
        }
        return "";
    }
}
